package com.ruicar.afs.cloud.afscase.externalinterface.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.afscase.common.utils.Const;
import com.ruicar.afs.cloud.afscase.externalinterface.condition.LoanAmountCondition;
import com.ruicar.afs.cloud.afscase.externalinterface.mapper.ExternalLoanAmountMapper;
import com.ruicar.afs.cloud.afscase.externalinterface.service.ExternalLoanAmountService;
import com.ruicar.afs.cloud.afscase.externalinterface.vo.ExternalLoanAmountVo;
import com.ruicar.afs.cloud.afscase.externalinterface.vo.ExternalLoansVo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.postloan.config.ContractBasicSysConfig;
import com.ruicar.afs.cloud.basic.outer.api.common.dto.BasicExternalLoanAmountDto;
import com.ruicar.afs.cloud.basic.outer.api.common.feign.CommonOuterQueryFeign;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ContractStatusEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiaqi.guo
 * @version 1.0
 * @description: 对外提供集合接口
 * @created 2020/7/21 15:49
 */
@Service
@AllArgsConstructor
@Data
@Slf4j
public class ExternalLoanAmountServiceImpl extends ServiceImpl<ExternalLoanAmountMapper, ExternalLoansVo> implements ExternalLoanAmountService {
    /**
     * Common outer query feign
     */
    private CommonOuterQueryFeign commonOuterQueryFeign;
    /**
     * Contract basic sys config
     */
    private ContractBasicSysConfig contractBasicSysConfig;

    private CaseContractInfoService  caseContractInfoService;
    /**
     * 根据 共借人和主借人证件号码查询
     */
    public List<ExternalLoanAmountVo> getLoanAmountHistory(String borrowerCertno, String coborrowerCertno) {
        LoanAmountCondition amountCondition = new LoanAmountCondition();
        //证件号码
        List<String> certNoList = new ArrayList<>();
        certNoList.add(borrowerCertno);
        certNoList.add(coborrowerCertno);
        amountCondition.setCertNo(certNoList);
        //业务状态（内）
        List stateList = new ArrayList();
        stateList.add(AfsEnumUtil.key(BusinessStateInEnum.DRAFT));
        stateList.add(AfsEnumUtil.key(BusinessStateInEnum.CANCEL));
        stateList.add(AfsEnumUtil.key(BusinessStateInEnum.REJECT));
        stateList.add(AfsEnumUtil.key(BusinessStateInEnum.REPEAL));
        stateList.add(AfsEnumUtil.key(BusinessStateInEnum.CANCEL_ADVICE_CONDITIONAL));
        stateList.add(AfsEnumUtil.key(BusinessStateInEnum.REVISE_PARSE));
        amountCondition.setBusinessStatusList(stateList);

        List<ExternalLoansVo> list = this.baseMapper.getLoanAmountHistory(amountCondition);
        List<ExternalLoanAmountVo> amountVoList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(list)) {
            for (ExternalLoansVo amountVo : list) {
                if(StringUtils.isBlank(amountVo.getContractStatus())
                        ||(StringUtils.isNotBlank(amountVo.getContractStatus())&&!amountVo.getContractStatus().equals(ContractStatusEnum.contractEffective.getDesc()))){
                    ExternalLoanAmountVo loanAmountVo = new ExternalLoanAmountVo();
                    loanAmountVo.setId(amountVo.getId());
                    loanAmountVo.setLoanAmount(amountVo.getLoanAmount());
                    loanAmountVo.setApplicationNo(amountVo.getApplicationNo());
                    amountVoList.add(loanAmountVo);
                }
            }
            log.info("历史贷款金额有返回结果" + list.size());
        } else {
            log.info("历史贷款金额无返回结果");
        }

        /**获取合同系统剩余本金*/
        IResponse<List<BasicExternalLoanAmountDto>> response =commonOuterQueryFeign.loanhistoryFromContract(borrowerCertno,coborrowerCertno,contractSysHeaders());
        if (CommonConstants.SUCCESS.equals(response.getCode())) {
            List<BasicExternalLoanAmountDto> basicDtoList = response.getData();
            if(CollectionUtils.isNotEmpty(basicDtoList)){
                basicDtoList.forEach(basic -> {
                    CaseContractInfo caseContractInfo=caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                            .eq(CaseContractInfo::getContractNo,basic.getApplicationNo()));
                    basic.setApplicationNo(caseContractInfo.getApplyNo());
                    ExternalLoanAmountVo loanAmountVo = new ExternalLoanAmountVo();
                    loanAmountVo.setId(basic.getId());
                    loanAmountVo.setLoanAmount(basic.getLoanAmount());
                    loanAmountVo.setApplicationNo(caseContractInfo.getApplyNo());
                    amountVoList.add(loanAmountVo);
                });
            }
        }else{
            log.info("获取合同系统剩余本金无返回结果");
        }
        return amountVoList;

    }
    /**
     * @description:
     * @author jiaqi.guo
     * @created 2020/10/10 22:04
     * @version 1.0
     */
    public Map contractSysHeaders(){
        Map<String,String> headers = new HashMap<>();
        headers.put(Const.HTTP_HEADER_CLIENT_ID, contractBasicSysConfig.getClientId());
        headers.put(Const.HTTP_HEADER_CLIENT_SECRET,contractBasicSysConfig.getClientSecret());
        return headers;
    }
}
